package com.xiang.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiang.annotation.RepeatSubmit;
import com.xiang.redis.RedisCache;
import com.xiang.wrapper.RepeatableReadRequestWrapper;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class RepeatSubmitInterceptor implements HandlerInterceptor {

  public static final String REPEAT_PARAMS = "repeat_params";
  public static final String REPEAT_TIME = "repeat_time";
  public static final String REPEAT_SUBMIT_KEY = "repeat_submit_key:";

  @Autowired
  RedisCache redisCache;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      Method method = handlerMethod.getMethod();
      RepeatSubmit repeatSubmit = method.getAnnotation(RepeatSubmit.class);
      if (repeatSubmit != null) {
        if (isRepeatSubmit(request, repeatSubmit)) {
          Map<String, Object> map = new HashMap<>();
          map.put("status", 500);
          map.put("message", repeatSubmit.message());
          response.setContentType("application/json;charset=utf-8");
          response.getWriter().write(new ObjectMapper().writeValueAsString(map));
          return false;
        }
      }
    }
    return true;
  }

  /**
   * 判断是否是重复提交
   * @param request
   * @param repeatSubmit
   * @return
   */
  private boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit repeatSubmit) {
    // 请求参数字符串
    String nowParams = "";
    // 请求参数是 json 格式
    if (request instanceof RepeatableReadRequestWrapper) {
      try {
        //todo: 可以过滤body不需要参数
        nowParams = request.getReader().lines().collect(Collectors.joining());
        log.info("body 参数： {}",nowParams);

      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    // 请求参数是 kay-value 格式
    if (StringUtils.isEmpty(nowParams)) {
      try {
        nowParams = new ObjectMapper().writeValueAsString(request.getParameterMap());
      } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
      }
    }
    Map<String, Object> nowDataMap = new HashMap<>();
    nowDataMap.put(REPEAT_PARAMS, nowParams);
    nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
    String requestURI = request.getRequestURI();
    String requestHeaders = getRequestHeader(request, repeatSubmit.headers());
    //请求参数=请求头部+URI+请求body  hash值
    String requestParamSign =  REPEAT_SUBMIT_KEY + DigestUtils.sha1Hex(requestHeaders+ requestURI + nowParams);
    log.info("request hash key: {}",requestParamSign);
    Object cacheObject = redisCache.getCacheObject(requestParamSign);
    if (cacheObject != null) {
      Map<String, Object> map = (Map<String, Object>) cacheObject;
      if (compareParams(map, nowDataMap) && compareTime(map, nowDataMap, repeatSubmit.interval())) {
        return true;
      }
    }
    redisCache.setCacheObject(requestParamSign, nowDataMap, repeatSubmit.interval(), TimeUnit.MILLISECONDS);
    return false;
  }

  /**
   * 获取指定请求头部参数
   * @param request
   * @param customerHeaders
   * @return
   */
  private String getRequestHeader(HttpServletRequest request, String[] customerHeaders){
    if (customerHeaders.length == 0) {
      return "empty";
    }
    StringBuilder sb = new StringBuilder();
    for (String headerKey : customerHeaders) {
      sb.append(request.getHeader(headerKey));
    }
    return sb.toString();
  }

  private boolean compareTime(Map<String, Object> map, Map<String, Object> nowDataMap, int interval) {
    Long time1 = (Long) nowDataMap.get(REPEAT_TIME);
    Long time2 = (Long) map.get(REPEAT_TIME);
    if ((time1 - time2) < interval) {
      return true;
    }
    return false;
  }

  private boolean compareParams(Map<String, Object> map, Map<String, Object> nowDataMap) {
    String params1 = (String) nowDataMap.get(REPEAT_PARAMS);
    String params2 = (String) map.get(REPEAT_PARAMS);
    return params1.equals(params2);
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
  }
}
